package com.example.node.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.node.entity.BladeDept;
import com.example.node.mapper.BladeDeptMapper;
import com.example.node.service.BladeDeptService;
import com.example.node.util.ForestNodeMerger;
import com.example.node.vo.TreeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yangss
 * @since 2023-11-29
 */
@Service
public class BladeDeptServiceImpl extends ServiceImpl<BladeDeptMapper, BladeDept> implements BladeDeptService {
    @Autowired
    private BladeDeptMapper bladeDeptMapper;

    @Override
    public List<BladeDept> tree(String tenantId) {
        List<BladeDept> tree = bladeDeptMapper.tree(tenantId);
        //测试
        return ForestNodeMerger.merge(tree);
    }

    @Override
    public String deptTree() {
        List<BladeDept> tree = bladeDeptMapper.tree("000000");
        List<Long> collect = tree.stream().map(BladeDept::getParentId).collect(Collectors.toList());
        //构建node列表
        List<TreeVO> treeVOS = new ArrayList<>();
        for (BladeDept bladeDept : tree){
            TreeVO treeVO = new TreeVO();
            treeVO.setId(bladeDept.getId().toString());
            treeVO.setParentId(bladeDept.getParentId().toString());
            treeVO.setName(bladeDept.getDeptName());
            treeVO.setOrder(bladeDept.getSort().toString());
            treeVO.setHasChildren(false);
            treeVO.setType("dept");
            if (collect.contains(Long.valueOf(treeVO.getId()))){
                treeVO.setHasChildren(true);
            }
            treeVOS.add(treeVO);
        }

        for (int i = 0; i < 3 ; i++){
            TreeVO treeVO = new TreeVO();
            treeVO.setId("123456"+i);
            treeVO.setParentId("123456");
            treeVO.setName("aa"+i);
            treeVO.setOrder("1"+i);
            treeVO.setHasChildren(false);
            treeVO.setType("user");
            treeVOS.add(treeVO);
        }

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setWeightKey("order");
        treeNodeConfig.setIdKey("id");

        List<Tree<String>> treeList = TreeUtil.build(treeVOS, "666", treeNodeConfig, (treeNode, node) -> {
            node.setId(treeNode.getId());
            node.setParentId(treeNode.getParentId());
            node.setWeight(treeNode.getOrder());
            node.setName(treeNode.getName());
            node.putExtra("type", treeNode.getType());
            node.putExtra("hasChildren",treeNode.getHasChildren());
        });
        return JSONUtil.toJsonStr(treeList);
    }
}
